package models

import (
	"github.com/beego/beego/v2/client/orm"
)

type ErpEntryreturn struct {
	Id                 int64
	DepartmentId       int64
	Suppliers          *ErpSuppliers `orm:"rel(fk);null;on_delete(do_nothing)"`
	Number             string
	Auditing           int     //审核状态0待添加，1已提交,2已出库
	Money              float64 //总金额
	Postage            float64 //邮费
	ProNumber          int64   //产品数量
	PayMethod          int
	DeliveryMode       int
	OutUser            string
	OutDate            string
	Remarks            string
	CreatedAt          int64
	UpdatedAt          int64
	CreatedBy          string
	UpdatedBy          string
	ErpEntryData       []*ErpEntryreturnData `orm:"reverse(many)"`
	StorageNum         int64
	TotalTaxPrice      float64 `orm:"-"` //总税额
	TotalDiscountPrice float64 `orm:"-"` //总折扣额
	TotalPreTax        float64 `orm:"-"` //总税前
	TotalTaxAfter      float64 `orm:"-"` //总税后
}

//查询
type ErpEntryreturnQueryParam struct {
	BaseQueryParam
	Filter       string
	Auditing     int
	DepartmentId int64
}

func (a *ErpEntryreturn) TableName() string {
	return ErpEntryreturnTableName()
}

func ErpEntryreturnTableName() string {
	return TableName("erp_entryreturn")
}

func ErpEntryreturnPageList(params *ErpEntryreturnQueryParam) ([]*ErpEntryreturn, int64) {

	ls := make([]*ErpEntryreturn, 0)

	query := orm.NewOrm().QueryTable(ErpEntryreturnTableName()).RelatedSel("Suppliers")

	if len(params.Filter) > 0 {
		query = query.Filter("number__istartswith", params.Filter)
	}

	if params.Auditing > 0 {
		query = query.Filter("auditing", params.Auditing)
	}

	if params.DepartmentId > 0 {
		query = query.Filter("department_id", params.DepartmentId)
	}

	sortorder := "-Id"

	switch params.Sort {
	case "Id":
		sortorder = "Id"
	}
	if params.Order == "desc" {
		sortorder = "-" + sortorder
	}

	total, _ := query.Count()

	query.OrderBy(sortorder).Limit(params.Limit, params.Offset).All(&ls)

	return ls, total
}

func GetErpEntryreturnById(id int64) (*ErpEntryreturn, error) {

	r := new(ErpEntryreturn)
	err := orm.NewOrm().QueryTable(ErpEntryreturnTableName()).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}

	return r, nil
}

func ErpEntryreturnAdd(c *ErpEntryreturn) (int64, error) {
	return orm.NewOrm().Insert(c)
}

func (a *ErpEntryreturn) ErpEntryreturnEdit(filter ...string) error {
	if _, err := orm.NewOrm().Update(a, filter...); err != nil {
		return err
	}
	return nil
}

//按时间段
func QueryErpEntryreturnTimeSoltSeterCount(starttime, endtime int64) int64 {
	count, _ := queryEntryTimeSoltSeter(starttime, endtime).Count()
	return count
}

func queryErpEntryreturnTimeSoltSeter(starttime, endtime int64) orm.QuerySeter {
	query := orm.NewOrm().QueryTable(ErpEntryreturnTableName())

	cond := orm.NewCondition()
	cond = cond.AndCond(cond.And("created_at__gte", starttime).And("created_at__lte", endtime))
	cond = cond.And("is_temp", 0)
	query = query.SetCond(cond)

	return query
}
